import 'package:chat_ai_demo/dao/completion_dao.dart';
import 'package:chat_ai_demo/dao/message_dao.dart';
import 'package:chat_ai_demo/db/db_manage.dart';
import 'package:chat_ai_demo/widget/msg_input.dart';
import 'package:chat_msg_demo/core/chat_controller.dart';
import 'package:chat_msg_demo/model/message_model.dart';
import 'package:chat_msg_demo/widget/chat_list.dart';
import 'package:flutter/material.dart';

class ConversationPage extends StatefulWidget {
  final int cid;

  const ConversationPage({super.key, required this.cid});

  @override
  State<ConversationPage> createState() => _ConversationPageState();
}

class _ConversationPageState extends State<ConversationPage> {
  bool _sendBtnEnable = true;
  String _inputMsg = '';
  ChatController? chatController;
  late MessageDao messageDao;
  final ScrollController _scrollController = ScrollController();
  List<MessageModel> _messageList = [];

  Widget get _chatList {
    if (chatController == null) {
      return const Expanded(child: Center(child: CircularProgressIndicator()));
    }
    return Expanded(child: ChatList(chatController: chatController!));
  }

  String get _title => _sendBtnEnable ? 'Deepseek Chat' : '正在思考...';

  Widget _buildInputWidget() {
    return MsgInputWidget(
      '输入您的问题...',
      onChange: (text) => _inputMsg = text,
      onSend: _onSend,
      maxLines: 3,
      maxLength: 2000,
    );
  }

  @override
  void initState() {
    super.initState();
    _dbInit();
  }

  @override
  void dispose() {
    chatController?.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(_title)),
      body: Column(children: [_chatList, _buildInputWidget()]),
    );
  }

  Future<void> _onSend() async {
    if (_inputMsg.trim().isEmpty || chatController == null) return;

    setState(() {
      _sendBtnEnable = false;
    });

    final userMessage = MessageModel(
      ownerType: OwnerType.sender,
      content: _inputMsg,
      avatar:
          'https://images.pexels.com/photos/30753562/pexels-photo-30753562.jpeg?auto=compress&cs=tinysrgb&w=600&lazy=load',
      ownerName: 'User',
    );

    chatController!.addMessage(userMessage);
    try {
      await messageDao.sendMessage(userMessage);

      final history = await messageDao.getMessage(pageSize: 3);

      String? response = '';
      response = await CompletionDao.createCompleations(
        prompt: _inputMsg,
        history: history,
      );

      if (!mounted) return;

      response ??= '抱歉，我现在无法回答您的问题。请稍后再试。';

      final assistantMessage = MessageModel(
        ownerType: OwnerType.receiver,
        content: response,
        avatar:
            'https://images.pexels.com/photos/8521518/pexels-photo-8521518.png?auto=compress&cs=tinysrgb&w=600&lazy=load',
        ownerName: 'Deepseek',
      );

      chatController!.addMessage(assistantMessage);
      await messageDao.sendMessage(assistantMessage);
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('错误: $e'), backgroundColor: Colors.red),
      );
      debugPrint(e.toString());
    } finally {
      if (mounted) {
        setState(() {
          _sendBtnEnable = true;
          _inputMsg = '';
        });
      }
    }
  }

  Future<void> _dbInit() async {
    final dbManager = await DBManage.instance(dbName: 'chat');
    messageDao = MessageDao(dbManager, cid: widget.cid);

    // 加载历史消息
    try {
      final messages = await messageDao.getMessage(pageSize: 1000);
      if (!mounted) return;

      setState(() {
        _messageList = List.from(messages.reversed);
        chatController = ChatController(
          timePellet: 60,
          initialMessageList: _messageList,
          scrollController: _scrollController,
        );
      });
    } catch (e) {
      print('Error loading messages: $e');
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('加载历史消息失败')));
      }
    }
  }

  int pageIndex = 1;

  Future<List<MessageModel>> _loadData({bool loadMore = false}) async {
    if (chatController == null) return [];

    if (loadMore) {
      pageIndex += 1;
    } else {
      pageIndex = 1;
    }
    var list = await messageDao.getMessage(pageIndex: pageIndex, pageSize: 20);
    debugPrint('加载消息: 第$pageIndex页, ${list.length}条');
    if (loadMore && list.isNotEmpty) {
      chatController!.loadMoreData(list);
    } else if (loadMore) {
      pageIndex -= 1;
    }
    return List.from(list.reversed);
  }
}
